package com.sdr.hkcamera;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.hik.mcrsdk.MCRSDK;
import com.hik.mcrsdk.rtsp.LiveInfo;
import com.hik.mcrsdk.rtsp.RtspClient;
import com.hikvision.vmsnetsdk.CameraInfo;
import com.hikvision.vmsnetsdk.CameraInfoEx;
import com.hikvision.vmsnetsdk.RealPlayURL;
import com.hikvision.vmsnetsdk.ServInfo;
import com.hikvision.vmsnetsdk.VMSNetSDK;
import com.hikvision.vmsnetsdk.netLayer.msp.deviceInfo.DeviceInfo;
import com.sdr.hkcamera.data.TempData;

import java.util.ArrayList;
import java.util.List;

public class HKMainActivity extends AppCompatActivity implements HKContract.View, LiveCallBack {

    private BlockListAdapter<HKDeviceInfo> adapter;
    private static Point point;
    private static FrameLayout container;
    private HKPresenter hkPresenter;
    private ProgressDialog pd;

    //    private LiveControl mLiveControl;
    private VMSNetSDK mVmsNetSDK;
    private ServInfo mServInfo;
    private String serAddr;
    private String sessionid;
    private RtspClient mRtspHandle;

    private ResourceListFragment resourceListFragment;
    private List<HKDeviceInfo> dataList = new ArrayList<HKDeviceInfo>();
    private int containerHeight;
    public int containerWidth;

    private int selectPosition;
    private BlockListView blockListView;
    private GestureDetectorCompat detector;
    private int lastTapPosition = -1;

    private final Handler mMessageHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.arg1) {
                case ConstantLive.RTSP_SUCCESS:
/*                    Toast.makeText(HKMainActivity.this, "启动取流成功", Toast.LENGTH_SHORT).show();*/
                    break;

                case ConstantLive.STOP_SUCCESS:
/*                    Toast.makeText(HKMainActivity.this, msg.what + "停止成功", Toast.LENGTH_SHORT).show();*/
                    dataList.get(msg.what).getCameraViewHolder().add.setVisibility(View.VISIBLE);
                    dataList.get(msg.what).getCameraViewHolder().del.setVisibility(View.GONE);
                    break;

                case ConstantLive.START_OPEN_FAILED:
                    Toast.makeText(HKMainActivity.this, "开启播放库失败", Toast.LENGTH_SHORT).show();
                    dataList.get(msg.what).getCameraViewHolder().progressBar.setVisibility(View.GONE);
                    dataList.get(msg.what).getCameraViewHolder().add.setVisibility(View.VISIBLE);
                    dataList.get(msg.what).getCameraViewHolder().del.setVisibility(View.GONE);
                    dataList.get(msg.what).getLiveControl().stop();
                    break;

                case ConstantLive.PLAY_DISPLAY_SUCCESS:
/*                    Toast.makeText(HKMainActivity.this, msg.what + "播放成功", Toast.LENGTH_SHORT).show();*/
                    dataList.get(msg.what).getCameraViewHolder().progressBar.setVisibility(View.GONE);
                    dataList.get(msg.what).getCameraViewHolder().del.setVisibility(View.VISIBLE);
                    break;

                case ConstantLive.RTSP_FAIL:
                    Toast.makeText(HKMainActivity.this, "RTSP链接失败", Toast.LENGTH_SHORT).show();
                    dataList.get(msg.what).getCameraViewHolder().progressBar.setVisibility(View.GONE);
                    dataList.get(msg.what).getCameraViewHolder().add.setVisibility(View.VISIBLE);
                    dataList.get(msg.what).getCameraViewHolder().del.setVisibility(View.GONE);

                    dataList.get(msg.what).getLiveControl().stop();
                    break;

                case ConstantLive.GET_OSD_TIME_FAIL:
                    Toast.makeText(HKMainActivity.this, "获取OSD时间失败", Toast.LENGTH_SHORT).show();
                    break;

                case ConstantLive.SD_CARD_UN_USEABLE:
                    Toast.makeText(HKMainActivity.this, "SD卡不可用", Toast.LENGTH_SHORT).show();
                    break;

                case ConstantLive.SD_CARD_SIZE_NOT_ENOUGH:
                    Toast.makeText(HKMainActivity.this, "SD卡空间不足", Toast.LENGTH_SHORT).show();
                    break;
                case ConstantLive.CAPTURE_FAILED_NPLAY_STATE:
                    Toast.makeText(HKMainActivity.this, "非播放状态不能抓拍", Toast.LENGTH_SHORT).show();
                    break;
                case ConstantLive.RECORD_FAILED_NPLAY_STATE:
                    Toast.makeText(HKMainActivity.this, "非播放状态不能录像", Toast.LENGTH_SHORT).show();
                    break;
                case ConstantLive.AUDIO_START_FAILED_NPLAY_STATE:
                    Toast.makeText(HKMainActivity.this, "非播放状态不能开启音频", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    private ArrayList<CameraInfo> tempList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getResources().getIdentifier("activity_hkmain", "layout", getPackageName()));

        System.loadLibrary("gnustl_shared");
        MCRSDK.init();
        RtspClient.initLib();
        MCRSDK.setPrint(1, null);
        mVmsNetSDK = VMSNetSDK.getInstance();
        mVmsNetSDK.openLog(false);
        mRtspHandle = RtspClient.getInstance();

        WindowManager wm = getWindowManager();
        point = new Point();
        wm.getDefaultDisplay().getSize(point);
        if (getSupportActionBar() != null){
            getSupportActionBar().setTitle("摄像头列表");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        blockListView = (BlockListView) findViewById(getResources().getIdentifier("gridView", "id", getPackageName()));
        container = (FrameLayout) findViewById(getResources().getIdentifier("container", "id", getPackageName()));
        findViewById(getResources().getIdentifier("grid_one", "id", getPackageName()))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (adapter.getCloumnNum() == 1)
                            return;
                        adapter.setColumnNum(1);
                        blockListView.onDataListChange();
                    }
                });
        findViewById(getResources().getIdentifier("grid_two", "id", getPackageName()))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (adapter.getCloumnNum() == 2)
                            return;
                        adapter.setColumnNum(2);
                        blockListView.onDataListChange();
                    }
                });
        findViewById(getResources().getIdentifier("grid_three", "id", getPackageName()))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (adapter.getCloumnNum() == 3)
                            return;
                        adapter.setColumnNum(3);
                        blockListView.onDataListChange();
                    }
                });
        findViewById(getResources().getIdentifier("grid_four", "id", getPackageName()))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (adapter.getCloumnNum() == 4)
                            return;
                        adapter.setColumnNum(4);
                        blockListView.onDataListChange();
                    }
                });
        findViewById(getResources().getIdentifier("clear", "id", getPackageName()))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tempList = new ArrayList<CameraInfo>();
                        for (int i = 0; i < dataList.size(); i++) {
                            HKDeviceInfo deviceInfooo = dataList.get(i);
                            tempList.add(deviceInfooo.getCameraInfo());
                            if (deviceInfooo.getCameraInfo() != null) {
                                deviceInfooo.setDeviceInfo(null);
                                deviceInfooo.setCameraInfo(null);
                                dataList.get(i).getCameraViewHolder().progressBar.setVisibility(View.GONE);
                                dataList.get(i).getCameraViewHolder().add.setVisibility(View.VISIBLE);
                                deviceInfooo.getLiveControl().stop();
                            }
                        }
                    }
                });
        findViewById(getResources().getIdentifier("restore", "id", getPackageName()))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (tempList == null)
                            return;

                        for (int i = 0; i < tempList.size(); i++) {
                            CameraInfo cameraInfo = tempList.get(i);
                            if (cameraInfo != null) {
                                dataList.get(i).setCameraInfo(cameraInfo);
                                dataList.get(i).getCameraViewHolder().progressBar.setVisibility(View.VISIBLE);
                                dataList.get(i).getCameraViewHolder().add.setVisibility(View.GONE);
                                new LiveControlAsyncTask().execute(i);
                            }
                        }
                        tempList = null;
                    }
                });
        detector =
                new GestureDetectorCompat(HKMainActivity.this, new GestureDetector.SimpleOnGestureListener() {
                    @Override
                    public boolean onSingleTapConfirmed(MotionEvent e) {

                        for (int i = 0; i < 16; i++) {
                            if (i == lastTapPosition) {
                                dataList.get(i).getCameraViewHolder().view
                                        .setBackgroundColor(Color.RED);
                            } else {
                                dataList.get(i).getCameraViewHolder().view
                                        .setBackgroundColor(Color.TRANSPARENT);
                            }
                        }
                        return super.onSingleTapConfirmed(e);
                    }

                    @Override
                    public boolean onDoubleTap(MotionEvent e) {

                        CameraInfo tempCameraInfo = dataList.get(lastTapPosition).getCameraInfo();
                        if (tempCameraInfo == null)
                            return super.onDoubleTap(e);
                        Intent intent = new Intent(HKMainActivity.this, HKCameraActivity.class);
                        intent.putExtra(HKCameraActivity.CAMERA_ID, tempCameraInfo.getId());
                        startActivity(intent);
                        return super.onDoubleTap(e);
                    }
                });
        initData();

        adapter = new BlockListAdapter<HKDeviceInfo>() {
            @Override
            public View getView(LayoutInflater layoutInflater, int position) {
                return dataList.get(position).getCameraViewHolder().view;
            }
        };

        container.post(new Runnable() {
            @Override
            public void run() {
                containerHeight = container.getHeight();
                containerWidth = container.getWidth();
                adapter.setSpace(5, 5);
                adapter.setBlockSize(containerWidth / 3, containerHeight / 3);
                adapter.setColumnNum(3);
                blockListView.setAdapter(adapter);
                adapter.displayBlocks(dataList);
            }
        });

        if (hkPresenter == null) {
            hkPresenter = new HKPresenter();
            hkPresenter.attach(this, this);
        }

        String url = getIntent().getStringExtra("url");
        String username = getIntent().getStringExtra("username");
        String password = getIntent().getStringExtra("password");

        if(TextUtils.isEmpty(url) || TextUtils.isEmpty(username) || TextUtils.isEmpty(password)){
            Toast.makeText(this,"用户名密码无效",Toast.LENGTH_SHORT).show();
            return;
        }

        pd = new ProgressDialog(this);
        pd.setCancelable(false);
        pd.setMessage("登录中...");
        pd.show();
        hkPresenter.login(url, username, password, getMacAddr());

    }

    private void initData() {
        for (int i = 0; i < 16; i++) {
            final int tt = i;
            LiveControl temp = new LiveControl(tt);
            temp.setLiveCallBack(HKMainActivity.this);

            HKDeviceInfo deviceInfo = new HKDeviceInfo();
            deviceInfo.setLiveControl(temp);

            final CameraViewHolder cameraViewHolder =
                    new CameraViewHolder(this,View.inflate(HKMainActivity.this, getResources()
                                    .getIdentifier("camera_item", "layout", getPackageName())
                            , null), i);
            deviceInfo.setCameraViewHolder(cameraViewHolder);

            dataList.add(deviceInfo);

            cameraViewHolder.surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
                @Override
                public void surfaceCreated(SurfaceHolder holder) {
                    final HKDeviceInfo hkDeviceInfo = dataList.get(tt);
                    if (hkDeviceInfo.getCameraInfo() != null) {
                        hkDeviceInfo.getCameraViewHolder().progressBar.setVisibility(View.VISIBLE);
                        hkDeviceInfo.getCameraViewHolder().add.post(new Runnable() {
                            @Override
                            public void run() {
                                hkDeviceInfo.getCameraViewHolder().add.setVisibility(View.GONE);
                            }
                        });
                        new LiveControlAsyncTask().execute(tt);
                    }
                }

                @Override
                public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                }

                @Override
                public void surfaceDestroyed(SurfaceHolder holder) {
                    HKDeviceInfo hkDeviceInfo = dataList.get(tt);
                    if (hkDeviceInfo.getCameraInfo() != null) {
                        hkDeviceInfo.getLiveControl().stop();
                    }
                }
            });

            cameraViewHolder.add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(resourceListFragment == null)
                        return;
                    HKMainActivity.this.getSupportFragmentManager().beginTransaction()
                            .replace(getResources().getIdentifier("fragment_container","id",getPackageName()), resourceListFragment, "list").commit();
                    selectPosition =Integer.parseInt(v.getTag().toString());
                }
            });
            cameraViewHolder.del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    HKDeviceInfo deviceInfo = dataList.get((Integer) v.getTag());
                    if (deviceInfo.getCameraInfo() != null && deviceInfo.getDeviceInfo() != null) {
                        deviceInfo.setCameraInfo(null);
                        deviceInfo.setDeviceInfo(null);
                        deviceInfo.getLiveControl().stop();
                    }
                }
            });

            cameraViewHolder.view.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    lastTapPosition = Integer.parseInt(cameraViewHolder.view.getTag().toString());
                    detector.onTouchEvent(event);
                    return false;
                }
            });
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home)
            finish();
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void loginSuccess() {
        pd.setMessage("获取摄像头组织结构中...");
        Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
        //init
        mServInfo = TempData.getInstance().getLoginData();
        serAddr = TempData.getInstance().getServerAddr();
        sessionid = mServInfo.getSessionID();
        hkPresenter.loadNodeList();
    }

    @Override
    public void loginFail() {
        pd.dismiss();
        Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
        //        finish();
        // TODO 结束界面

    }

    @Override
    public void loadNodeResult(boolean isSuccess) {
        pd.dismiss();
        resourceListFragment = new ResourceListFragment();
        resourceListFragment.setCameraClickCallback(new ResourceListFragment.CameraCallback() {
            @Override
            public void clickCamera() {
                HKDeviceInfo deviceInfo = dataList.get(selectPosition);
                deviceInfo.setCameraInfo(TempData.getInstance().getCameraInfo());
                deviceInfo.getCameraViewHolder().add.setVisibility(View.GONE);
                deviceInfo.getCameraViewHolder().progressBar.setVisibility(View.VISIBLE);

                new LiveControlAsyncTask().execute(selectPosition);
            }
        });

        if (!isSuccess) {
            Toast.makeText(this, "获取摄像头组织结构失败", Toast.LENGTH_SHORT).show();
            //TODO 结束界面
        } else {
            Toast.makeText(this, "获取摄像头组织结构成功", Toast.LENGTH_SHORT).show();
        }
    }

    //获取mac地址
    protected String getMacAddr() {
        WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        String mac = wm.getConnectionInfo().getMacAddress();
        return mac == null ? "" : mac;
    }

    @Override
    public void onMessageCallback(int message, int index) {
        Message msg = Message.obtain();
        msg.arg1 = message;
        msg.what = index;
        mMessageHandler.sendMessage(msg);
    }

    class LiveControlAsyncTask extends AsyncTask<Integer, Void, Boolean> {

        DeviceInfo deviceInfo = new DeviceInfo();
        String url;

        @Override
        protected Boolean doInBackground(Integer... params) {
            boolean ret;
            HKDeviceInfo hkDeviceInfo = dataList.get(params[0]);

            int streamType = ConstantLive.SUB_STREAM;
            CameraInfoEx cameraInfoEx = new CameraInfoEx();
            cameraInfoEx.setId(hkDeviceInfo.getCameraInfo().getId());
            RealPlayURL mRealPlayURL = new RealPlayURL();

            ret = mVmsNetSDK.getCameraInfoEx(serAddr, sessionid, hkDeviceInfo.getCameraInfo().getId(), cameraInfoEx);
            if (!ret)
                return false;

            ret = mVmsNetSDK.getDeviceInfo(serAddr, sessionid, cameraInfoEx.getDeviceId(), deviceInfo);
            if (!ret || TextUtils.isEmpty(deviceInfo.getLoginName())
                    || TextUtils.isEmpty(deviceInfo.getLoginPsw())) {
                deviceInfo.setLoginName("admin");
                deviceInfo.setLoginPsw("12345");
            }

            String mToken = mVmsNetSDK.getPlayToken(sessionid);
            LiveInfo liveInfo = new LiveInfo();
            liveInfo.setMagIp(mServInfo.getMagServer().getMagStreamSerAddr());
            liveInfo.setMagPort(mServInfo.getMagServer().getMagStreamSerPort());
            liveInfo.setCameraIndexCode(cameraInfoEx.getId());
            liveInfo.setToken(mToken);
            // 转码不区分主子码流
            liveInfo.setStreamType(streamType);
            liveInfo.setMcuNetID(mServInfo.getAppNetId());
            liveInfo.setDeviceNetID(cameraInfoEx.getDeviceNetId());
            liveInfo.setiPriority(mServInfo.getUserAuthority());
            liveInfo.setCascadeFlag(cameraInfoEx.getCascadeFlag());
            if (deviceInfo != null) {
                if (cameraInfoEx.getCascadeFlag() == LiveInfo.CASCADE_TYPE_YES) {
                    deviceInfo.setLoginName("admin");
                    deviceInfo.setLoginPsw("12345");
                }
            }
            if (mServInfo.isInternet()) {
                liveInfo.setIsInternet(LiveInfo.NETWORK_TYPE_INTERNET);
                // 获取不转码地址
                liveInfo.setbTranscode(false);
                mRealPlayURL.setUrl1(mRtspHandle.generateLiveUrl(liveInfo));

                // 获取转码地址
                // 使用默认转码参数cif 128 15 h264 ps
                liveInfo.setbTranscode(true);
                mRealPlayURL.setUrl2(mRtspHandle.generateLiveUrl(liveInfo));
            } else {
                liveInfo.setIsInternet(LiveInfo.NETWORK_TYPE_LOCAL);
                liveInfo.setbTranscode(false);
                // 内网不转码
                mRealPlayURL.setUrl1(mRtspHandle.generateLiveUrl(liveInfo));
                mRealPlayURL.setUrl2("");
            }
            url = mRealPlayURL.getUrl1();
//                    if (streamType == 2 && mRealPlayURL.getUrl2() != null && mRealPlayURL.getUrl2().length() > 0) {
//                        url = mRealPlayURL.getUrl2();
//                    }
            hkDeviceInfo.setDeviceInfo(deviceInfo);
            hkDeviceInfo.setPlayUrl(url);
            dataList.set(params[0], hkDeviceInfo);

            hkDeviceInfo.getLiveControl().setLiveParams(hkDeviceInfo.getPlayUrl(),
                    hkDeviceInfo.getDeviceInfo().getLoginName(), hkDeviceInfo.getDeviceInfo().getLoginPsw());
            hkDeviceInfo.getLiveControl().startLive(hkDeviceInfo.getCameraViewHolder().surfaceView);

            return true;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {

            if (aBoolean) {
                Log.d("asyncTask", "。。。");
            } else {
                Log.e("HKCameraAdapter", "添加摄像头获取播放地址失败");
            }
        }
    }

}
